import java.util.*;

/**
 * @author LKQ
 * @date 2022/2/22 11:51
 * @description 哈希表 + 排序
 */
public class FormalSolution {
    public static void main(String[] args) {

    }
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> cnt = new HashMap<String, Integer>();
        for (String word : words) {
            cnt.put(word, cnt.getOrDefault(word, 0) + 1);
        }
        List<String> rec = new ArrayList<String>();
        for (Map.Entry<String, Integer> entry : cnt.entrySet()) {
            rec.add(entry.getKey());
        }
        rec.sort((word1, word2) -> Objects.equals(cnt.get(word1), cnt.get(word2)) ? word1.compareTo(word2) : cnt.get(word2) - cnt.get(word1));
        return rec.subList(0, k);
    }
}
